package net.lovesrc.allin.biz.sysconfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zhouzhou.fastjava.BizException;
import net.lovesrc.allin.BaseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class SysConfigService extends BaseBean {

    @Autowired
    private ConfigurableEnvironment environment;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void updateConfig(String key, Object value) {
        JSONObject configs = getConfigs();
        configs.put(key, value);
        saveConfigJson(configs);
    }

    public JSONObject getConfigs() {
        JSONObject row = queryForRow(jdbcTemplate, "select configs from t_sys_config");
        if (row == null) {
            return null;
        }
        return JSON.parseObject(row.getString("configs"));
    }

    public void saveConfigs(String configs) {
        JSONObject configJson;
        try {
            configJson = JSON.parseObject(configs);
        } catch (JSONException e) {
            throw BizException.messageOf("非法的json格式的配置");
        }
        saveConfigJson(configJson);
    }

    private synchronized void saveConfigJson(JSONObject configJson) {
        int count = jdbcTemplate.queryForObject("select count(1) from t_sys_config", int.class);
        if (count == 0) {
            jdbcTemplate.update("insert into t_sys_config(configs) values(?)", configJson.toJSONString());
        } else {
            jdbcTemplate.update("update t_sys_config set configs = ?", configJson.toJSONString());
        }

        // update environment
        environment.getPropertySources().addLast(
                new MapPropertySource("MySelf", configJson)
        );
    }

    @PostConstruct
    public void postConstruct() {
        JSONObject configJson = getConfigs();
        if (configJson == null) {
            return;
        }
        environment.getPropertySources().addLast(
                new MapPropertySource("MySelf", configJson)
        );
    }

}
